# coding:utf-8

__version__ = '0.0.1'
__autor__ = 'Seer'

'''
微博工具
'''

import sys
import json
import os
import time
import sqlite3
from weibo import APIClient

reload(sys)
sys.setdefaultencoding('utf-8')

timeFt = '%Y-%m-%d %H:%M:%S'
wb_client = None
sqlit_connection = None


def init_weibo():
    '''
    初始化微博参数
    :return:
    '''
    file_path = '{path}\\config.json'.format(
        path=sys.path[0]
    )
    config_str = open(file_path, 'r').read()

    config_json = json.loads(config_str)

    global wb_client
    wb_client = APIClient(
        app_key=config_json['app_key'],
        app_secret=config_json['app_secret'],
        redirect_uri=config_json['redirect_uri'],
    )
    wb_client.set_access_token(config_json['access_token'], config_json['expires_in'])


def init_sqlite():
    '''
    初始化数据库参数
    :return:
    '''
    global sqlit_connection
    db_file = '%s\\weibo.db' % sys.path[0]
    sqlit_connection = sqlite3.connect(db_file)


def save_data(id, created_at, text, original_pic, _json):
    '''
    保存数据
    :param id:
    :param create_at:
    :param text:
    :param original_pic:
    :param _json:
    :return:
    '''
    if not sqlit_connection:
        init_sqlite()
    sql = '''
        insert into weibobackup(id, created_at, text, original_pic,_json) VALUES ('%s','%s','%s','%s','%s')
        ''' % (id, created_at, text, original_pic, _json)
    print sql
    cursor = sqlit_connection.cursor()
    cursor.execute(sql)
    sqlit_connection.commit()


def wb_time(GMT_time):
    '''
    微博时间转换
    :param GMT_time:
    :return:
    '''
    GMT_FORMAT = '%a %b %d %H:%M:%S +0800 %Y'
    time_tmp = time.strptime(GMT_time, GMT_FORMAT)
    return time.strftime(timeFt, time_tmp)


def backup_weibo():
    '''
    备份微博原创内容
    :return:
    '''

    '''
    没啥用了。。
    
    此接口最多只返回最新的5条数据，官方移动SDK调用可返回10条；
    
    还是用爬虫吧 
    '''
    try:

        # 初始化微博客户端
        if not wb_client:
            init_weibo()

        for i in range(1, 8):
            weibo_content = wb_client.statuses.user_timeline.get(count=100, feature=1, page=i)

            for statuses in weibo_content.statuses:
                id = statuses.id,
                created_at = statuses.created_at,
                text = statuses.text,
                text = '%s' % text

                if statuses.__contains__('original_pic'):
                    original_pic = statuses.original_pic
                else:
                    original_pic = None

                _json = weibo_content

                created_at = wb_time(created_at[0])

                id = '%d' % id
                _json = '%s' % _json
                _json = _json.replace('\'', '\"')

                # 保存
                save_data(
                    id=id,
                    created_at=created_at,
                    text=text,
                    original_pic=original_pic,
                    _json=_json
                )
    except Exception, e:
        print e
    finally:
        if sqlit_connection:
            sqlit_connection.close()


if __name__ == '__main__':
    init_weibo()
    backup_weibo()
